package com.jingge.autojob.skeleton.cluster.balancing;

import com.jingge.autojob.skeleton.cluster.api.ClusterAPI;
import com.jingge.autojob.skeleton.cluster.dto.ClusterMessage;
import com.jingge.autojob.skeleton.cluster.model.ClusterNode;
import com.jingge.autojob.skeleton.framework.network.client.CachedProxyClient;
import com.jingge.autojob.skeleton.framework.task.AutoJobTask;
import com.jingge.autojob.skeleton.lifecycle.TaskEventFactory;
import com.jingge.autojob.skeleton.lifecycle.event.imp.TaskMissFireEvent;
import com.jingge.autojob.skeleton.lifecycle.manager.TaskEventManager;
import com.jingge.autojob.skeleton.model.register.AutoJobRegisterRefusedException;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-09-25 10:32
 * @email 1158055613@qq.com
 */
public class DowngradingStrategy implements LoadBalancingStrategy {
    private final CachedProxyClient<ClusterAPI> clusterAPICachedProxyClient = new CachedProxyClient<>(3, ClusterAPI.class);


    @Override
    public ClusterNode choose(List<ClusterNode> solves, AutoJobTask task) {
        for (ClusterNode solve : solves) {
            try {
                if (clusterAPICachedProxyClient
                        .getInstance(solve)
                        .isAlive(new ClusterMessage())) {
                    return solve;
                }
            } catch (Exception ignored) {
            }
        }
        TaskEventManager
                .getInstance()
                .publishTaskEvent(TaskEventFactory.newTaskMissFireEvent(task), TaskMissFireEvent.class, true);
        return null;
    }
}
